﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Collections;
using Telerik.Web.UI;
using DCSLibrary;
using System.Xml;
using System.Text;
using System.Data;
using Utils;
using Utils.DC.Web.UI;
using System.Configuration;
using Utils.DCSControl;

/// <summary>
/// Cac ham dung chung danh cho cac lap trinh vien viet
/// </summary>
public class General
{
    public General()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static string CheckLanguage()
    {
        return HttpContext.Current.Session["Lang"] != null ? HttpContext.Current.Session["Lang"].ToString() : "vn";
    }

    public static int MinuteBeforeMatch
    {
        get { return Convert.ToInt32(ConfigurationManager.AppSettings["MinuteBeforeMatch"]); }
    }

    public static String GenUrlPath(int parentID, string categoryPageName, DataSet dsFunctionPage)
    {
        try
        {
            return Utils.DC.Web.UI.WebUtility.GetParentUrl(parentID, dsFunctionPage.Tables[0]).Trim() + categoryPageName.Trim() + ".aspx";
        }
        catch (Exception e)
        {
            return "";
        }
    }

    /// <summary>
    /// Cat 1 doan text co so ky tu dai hon 200 ve dung 200 + ...
    /// </summary>
    /// <param name="text"></param>
    public static string CutString(string text)
    {
        if (text.Length > 200)
        {
            return text.Substring(0,200) + " ...";
        }
        else
        {
            return text;
        }
    }

    public static String GenUrlPath(string parentURL, string pageName)
    {
        return parentURL.Substring(0, parentURL.IndexOf(".aspx")) + "/" + pageName + ".aspx";
    }

    public static string FormatNumber(object objPrice)
    {
        string price = objPrice.ToString().Trim();
        string formatPrice = "";
        int count = 1;
        for (int i = price.Length - 1; i >= 0; i--)
        {
            formatPrice = price[i] + formatPrice;
            if (count == 3 && i != 0)
            {
                formatPrice = "." + formatPrice;
                count = 1;
            }
            else
            {
                count++;
            }
        }
        return formatPrice + " VND";
    }

    /// <summary>
    /// Ham dung de set gia tri duoc select trong drop down list (control asp.net)
    /// </summary>
    /// <param name="item">Gia tri can select</param>
    /// <param name="comobobox">dropdownlist</param>
    public static void SetSelectedItemInComboBox(string item, DropDownList comboBox)
    {
        if (item != null && item != "")
        {
            int index = 0;
            IEnumerator ie = comboBox.Items.GetEnumerator();
            ListItem listItem = null;
            while (ie.MoveNext())
            {
                listItem = (ListItem)ie.Current;
                if (listItem.Value == item)
                {
                    comboBox.SelectedIndex = index;
                    break;
                }
                index++;
            }
        }
        else if(comboBox.Items.Count > 0)
        {
            comboBox.SelectedIndex = 0;
        }
    }

    public static string[] Prizes
    {
        get
        {
            return new string[] { "Giải đặc biệt", "Giải nhất", "Giải nhì", "Giải ba", "Giải tư", "Giải năm", "Giải sáu", "Giải bảy", "Giải tám" };
        }
    }

    public static string LocationSession
    {
        get { return "LocationID"; }
    }
        
    /// <summary>
    /// Ham dung de set gia tri duoc select trong radcombobox (control telerik)
    /// </summary>
    /// <param name="item">Gia tri can select</param>
    /// <param name="comobobox">radcombobox</param>
    public static void SetSelectedItemInComboBox(string item, RadComboBox comboBox)
    {
        if (item != null && item != "")
        {
            int index = 0;
            IEnumerator ie = comboBox.Items.GetEnumerator();
            RadComboBoxItem listItem = null;
            while (ie.MoveNext())
            {
                listItem = (RadComboBoxItem)ie.Current;
                if (listItem.Value == item)
                {
                    comboBox.SelectedIndex = index;
                    break;
                }
                index++;
            }
        }
        else if (comboBox.Items.Count > 0)
        {
            comboBox.SelectedIndex = 0;
        }
    }

    public static void WriteLog(HttpRequest Request, HttpServerUtility Sever)
    {
        new AnalyticsUI().Add( (Request.UrlReferrer != null ?Request.UrlReferrer.OriginalString:""), Request.RawUrl, DateTime.Now, Request.UserHostAddress, Request.UserAgent, false,Sever.MachineName);
    }

    public static string SetStringStyle(string str, int fontSize)
    {
        String[] strs = str.Split(' ');
        IEnumerator ie = strs.GetEnumerator();

        int i = 0;

        string result = "";

        result += "<div style='letter-spacing:-2px'>";
        while (ie.MoveNext())
        {
            string s = ie.Current.ToString();

            if (s.Trim() == "")
            {
                continue;
            }

            if (i % 2 == 0)
            {
                result += "<span style=\"font-size:" + fontSize + "px\" class=\"red_text\">" + s.Trim() + "</span> ";
            }
            else
            {
                result += "<span style=\"font-size:" + fontSize + "px\" class=\"black_text\">" + s.Trim() + "</span> ";
            }
            i++;
        }
        result += "</div>";
        return result;
    }

    public static string SetStringStyle(string str, int fontSize, string[] color)
    {
        String[] strs = str.Split(' ');
        IEnumerator ie = strs.GetEnumerator();

        int i = 0;

        string result = "";

        result += "<div style='letter-spacing:-1px;line-height:-1px;'>";
        while (ie.MoveNext())
        {
            string s = ie.Current.ToString();

            if (s.Trim() == "")
            {
                continue;
            }


            if (i % 2 == 0)
            {
                result += "<span style=\"color:" + color[0] + ";font-size:" + fontSize + "px\" class=\"red_text\">" + s.Trim() + "</span>";
            }
            else
            {
                result += "<span style=\"color:" + color[1] + ";font-size:" + fontSize + "px\" class=\"black_text\">" + s.Trim() + "</span>";
            }

            i++;
        }
        result += "</div>";
        return result;
    }

    //
    // Returns a string of six random digits.
    //

    public static string GenerateRandomCode()
    {
        string s = "";
        for (int i = 0; i < 6; i++)
            s = String.Concat(s, new Random().Next(10).ToString());
        return s;
    }
}

public class ChatContentWorker
{
    private static string FileName
    {
        get { return ConfigurationManager.AppSettings["ChatContentFile"]; }
    }

    private static int MessagePerChannel
    {
        get { return Convert.ToInt32(ConfigurationManager.AppSettings["MessagePerChannel"]); }
    }

    private static XmlDocument doc;

    public static string LoadMessage(string channelName)
    {
       doc = LoadMessgeContentFile();
       if (doc != null)
       {
           XmlNode channelNode = CheckChannelExist(channelName, true);
           if (channelNode != null && channelNode.ChildNodes.Count > 0)
           {
               string channelContent = "";
               foreach (XmlNode mess in channelNode.ChildNodes)
               {
                   channelContent += "<p><b>" + mess.ChildNodes[0].InnerText.Trim() + " (" + mess.ChildNodes[1].InnerText.Trim() + "): </b> " + mess.ChildNodes[2].InnerText.Trim() + "</p>";
               }
               return channelContent;
           }
           else
           {
               return "";
           }
       }
       else
       {
           return "";
       }
    }

    public static void WriteMessage(Message mess, string channelName)
    {
        doc = LoadMessgeContentFile();
        if(doc != null)
        {
            XmlNode channelNode = CheckChannelExist(channelName, true);
            if (channelNode != null)
            {
                try
                {
                    int messageCount = channelNode.ChildNodes.Count;
                    if (messageCount > ChatContentWorker.MessagePerChannel)
                    {
                        ArrayList alDeleteNode = new ArrayList();
                        for (int i = 0; i <= messageCount - ChatContentWorker.MessagePerChannel; i++)
                        {
                            alDeleteNode.Add(channelNode.ChildNodes[i]);
                        }

                        foreach (XmlNode node in alDeleteNode)
                        {
                            channelNode.RemoveChild(node);
                        }
                    }

                    XmlElement messageElement = doc.CreateElement("Message");
                    messageElement.InnerXml = "<From>" + mess.From + "</From><SentTime>" + mess.SendTime + "</SentTime><Content>" + mess.Content + "</Content>";
                    channelNode.AppendChild(messageElement);

                    doc.Save(ChatContentWorker.FileName);
                }
                catch (Exception e)
                {
                }
            }
        }
    }

    /// <summary>
    /// Hàm dùng để check xem đã có channel này chưa
    /// </summary>
    /// <param name="channelName">Tên channel</param>
    /// <param name="isCreateNew">Nếu chưa có thì tạo mới, có rồi thì thôi</param>
    /// <returns></returns>
    private static XmlNode CheckChannelExist(string channelName, bool isCreateNew)
    {
        try
        {
            XmlNode node = doc.SelectSingleNode("/ChatContent/Channel[@Name='" + channelName + "']");
            //Nếu không tìm thấy
            if (node == null)
            {
                //Nếu cho phép tạo mới thì tạo mới, sau đó check lại lần nữa cho chắc ăn
                //nhưng với tham số isCreateNew = false để nếu vẫn ko tạo mới được thì trả về null luôn
                if (isCreateNew)
                {
                    XmlElement element = doc.CreateElement("Channel");
                    element.SetAttribute("Name", channelName);
                    element.SetAttribute("CreateDate", Format.FormatVietNameDate(DateTime.Now));
                    doc.DocumentElement.AppendChild(element);
                    doc.Save(ChatContentWorker.FileName);
                    return CheckChannelExist(channelName, false);
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return node;
            }
        }
        catch (Exception e)
        {
            return null;
        }
    }

    private static XmlDocument LoadMessgeContentFile()
    {
        try
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(ChatContentWorker.FileName);
            return doc;
        }
        catch(Exception e)
        {
            return null;
        }
    }
}

public class Message
{
    public Message(string from, string sendTime, string content)
    {
        this.from = from;
        this.sendTime = sendTime;
        this.content = content;
    }

    public Message(string from, DateTime sendTime, string content)
    {
        this.from = from;
        this.sendTime = Format.FormatVietNameDateTime(sendTime);
        this.content = content;
    }

    private string from;

    public string From
    {
        get { return from; }
        set { from = value; }
    }
    private string sendTime;

    public string SendTime
    {
        get { return sendTime; }
        set { sendTime = value; }
    }
    private string content;

    public string Content
    {
        get { return content; }
        set { content = value; }
    }
}

/*
public class RealTimeUser
{
    private int userID;

    public int UserID
    {
        get { return userID; }
        set { userID = value; }
    }

    private string clientID;

    public string ClientID
    {
        get { return clientID; }
        set { clientID = value; }
    }

    private string userName;

    public string UserName
    {
        get { return userName; }
        set { userName = value; }
    }

    private string channelName;

    public string ChannelName
    {
        get { return channelName; }
        set { channelName = value; }
    }

    public RealTimeUser() { }

    public RealTimeUser(string userName, string channelName)
    {
        //this.userID = userID;
        this.userName = userName;
        this.channelName = channelName;
    }
}
*/
/// <summary>
/// Summary description for Chat.
/// </summary>
public class Chat
{
    static protected ArrayList pArray = new ArrayList();


    static public void AddMessage(string sDealer, string sUser, string sMsg)
    {
        string sAddText = sDealer + "~" + sUser + "~" + sMsg;
        pArray.Add(sAddText);

        if (pArray.Count > 200)
        {
            pArray.RemoveRange(0, 10);
        }
    }

    static public string GetAllMessages(string sDealer)
    {
        string sResponse = "";

        for (int i = 0; i < pArray.Count; i++)
        {
            sResponse = sResponse + FormatChat(pArray[i].ToString(), sDealer);
        }

        return (sResponse);
    }

    static private string FormatChat(string sLine, string sDealer)
    {
        int iFirst = sLine.IndexOf("~");
        int iLast = sLine.LastIndexOf("~");

        string sDeal = sLine.Substring(0, iFirst);
        if (sDeal != sDealer)
            return ("");

        string sUser = sLine.Substring(iFirst + 1, iLast - (iFirst + 1));

        string sMsg = sLine.Substring(iLast + 1);

        string sRet = "<STRONG>" + sUser + ": </STRONG>" + sMsg + "<BR>";

        return (sRet);
    }
}

/*
public class RealTimeChat
{
    public static Hashtable Users = null;
    public static Hashtable Names = null;
    string ClientID;
    string Username;

    public RealTimeChat(string clientId)
    {
        ClientID = clientId;
        Username = "";
    }

    ~RealTimeChat()
    {
        lock (Users)
        {
            Users.Remove(ClientID);
        }
    }

    public void SetName(string user_name)
    {
        if (Username != "")
        {
            PokeIn.Comet.CometWorker.SendToClient(ClientID, "alert('You already have an username!');");
            return;
        }
        bool duplicate = false;
        lock (Names)
        {
            duplicate = Names.ContainsKey(user_name);
        }
        if (duplicate)
            PokeIn.Comet.CometWorker.SendToClient(ClientID, "alert('Another user is using the name you choose!\\nPlease try another one.');");
        else
        {
            lock (Names)
            {
                Names.Add(user_name, ClientID);
            }

            lock (Users)
            {
                Users.Add(ClientID, user_name);
            }
            Username = user_name;
            PokeIn.Comet.CometWorker.SendToClient(ClientID, "UsernameSet('" + PokeIn.Comet.BrowserHelper.SafeParameter(user_name) + "');");

        }
    }

    public void SetNameWithChannel(string username, string channelName)
    {
        //if (Username != "")
        //{
        //    PokeIn.Comet.CometWorker.SendToClient(ClientID, "alert('You already have an username!');");
        //    return;
        //}

        bool duplicate = false;
        lock (Names)
        {
            duplicate = Names.ContainsKey(username);
        }

        if (duplicate)
        {
            lock (Users)
            {
                ((RealTimeUser)Users[username]).ChannelName = channelName;
            }
            
            //PokeIn.Comet.CometWorker.SendToClient(ClientID, "alert('Another user is using the name you choose!\\nPlease try another one.');");
        }
        else
        {
            lock (Names)
            {
                Names.Add(Username, ClientID);
            }

            lock (Users)
            {
                Users.Add(ClientID, new RealTimeUser(Username, channelName));
            }

            Username = username;
            PokeIn.Comet.CometWorker.SendToAll("UsernameSet('" + PokeIn.Comet.BrowserHelper.SafeParameter(username) + "');");
        }
    }

    public void Send(string message)
    {
        PokeIn.Comet.CometWorker.SendToAll("ChatMessageFrom('" + PokeIn.Comet.BrowserHelper.SafeParameter(Username) + "','" + PokeIn.Comet.BrowserHelper.SafeParameter(message) + "');");
        ChatContentWorker.WriteMessage(new Message(Username, DateTime.Now, message), "abc");
    }

    /// <summary>
    /// Hàm gửi message chỉ cho những người đang ở cùng channel
    /// </summary>
    /// <param name="message"></param>
    /// <param name="chanelName"></param>
    public void SendWithChannel(string message, string chanelName)
    {
        RealTimeUser user = null;
        foreach (string clientID in Users.Keys)
        {
            user = (RealTimeUser)Users[clientID];
            if (user.ChannelName.ToLower() == chanelName.ToLower())
            {
                PokeIn.Comet.CometWorker.SendToClient(clientID, "ChatMessageFrom('" + PokeIn.Comet.BrowserHelper.SafeParameter(Username) + "','" + PokeIn.Comet.BrowserHelper.SafeParameter(message) + "');");
            }
        }
    }
}
 * 
 * */
 